/**
 * @MediatorObserverProxy.as
 * 
 * @author sodaChen mail:asframe@163.com
 * @version 1.0
 * <br>Copyright (C), 2010 asFrame.com
 * <br>This program is protected by copyright laws.
 * <br>Program Name:AStruts2
 * <br>Date:2012-4-6
 */
package com.asframe.astruts2.proxy
{
	import com.asframe.astruts2.beans.ViewBean;
	import com.asframe.astruts2.context.AStrutsData;
	import com.asframe.astruts2.controller.InitViewMediator;
	import com.asframe.astruts2.event.InitViewMediatorEvent;
	import com.asframe.pattern.observer.IObserver;
	
	/**
	 * Mediator的代理，当实现的Mediator角色非观察者以及不是单例等关系，通过该代理来实现对通知监听的相应
	 * @author sodaChen
	 * @Date:2012-4-6
	 */
	public class MediatorObserverProxy implements IObserver
	{
		private var isInit:Boolean;
		/** 接受到代处理的通知 **/
		private var notices:Array;
		/**  **/
		private var viewBean:ViewBean;
		private var astrutsData:AStrutsData;
		
		public function MediatorObserverProxy(viewBean:ViewBean,astrutsData:AStrutsData)
		{
			this.viewBean = viewBean;
			this.astrutsData = astrutsData;
		}
		
		public function replyNotice(notice:*, args:* = null):void
		{
			if(notices == null)
			{
				notices = [];
			}
			var ary:Array = null;
			if(args is Array)
			{
				ary = args;
			}
			else
			{
				ary = [args];
			}
			ary.unshift(notice);
			notices.push(ary);
			//进行初始化
			if(!isInit)
			{
				isInit = true;
				var initViewMediator:InitViewMediator = new InitViewMediator(viewBean,astrutsData);
				initViewMediator.addEventListener(InitViewMediatorEvent.INIT_OVER,onCompelete);
				initViewMediator.initViewMediator();
			}
		}
		
		private function onCompelete(event:InitViewMediatorEvent):void
		{
			isInit = false;
			var initViewMediator:InitViewMediator = event.target as InitViewMediator;
			initViewMediator.removeEventListener(InitViewMediatorEvent.INIT_OVER,onCompelete);
			//删除该View的MediatorObserverProxy，转换成实际的计算后的相关观察者
			var len:int = viewBean.observers.length;
			for (var i:int = 0; i < len; i++) 
			{
				astrutsData.subjects.removeObserver(viewBean.observerNotices[i],viewBean.observers[i]);
			}
			
			
			//初始化完毕，再发送一次通知
			for each (var noticeArgs:Array in notices) 
			{
				try
				{
					astrutsData.context.sendNotice.apply(astrutsData.context,noticeArgs);
				} 
				catch(error:Error) 
				{
					trace(error.getStackTrace());
				}
			}
		}
	}
}
